/**
 * <p><b>Title:</b> InitDataController.java </p>
 * @Package com.wondertek.poms.init.controller
 */
package com.wondertek.poms.init.controller;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.controller.BaseController;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.utils.MyThreadPool;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.init.config.InitConstants;
import com.wondertek.poms.init.po.InitData;
import com.wondertek.poms.init.service.IInitDataService;
import com.wondertek.poms.init.vo.InitDataVo;

import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * <p><b>InitDataController Description:</b> 初始化表 Controller层实现</p>
 * @author 窦再兴
 * <p><b>DATE</b> 2020-03-30 18:57:15</p>
 */
@Api("初始化 ")
@RestController
@Scope("prototype")
@RequestMapping(value="/init/data")
public class InitDataController extends BaseController {
	
	@Autowired
	private IInitDataService initDataService;
	@Resource
	private ThreadPoolTaskExecutor threadPoolD;
	
	@GetMapping("/config")
	public Map<String, Object> config() {
		Map<String, Object> map = getStatus();
		return map;
	}
	
	@GetMapping("/onOff/{onOff}")
	public Map<String, Object> onOff(@PathVariable int onOff) {
		InitConstants.OFF = onOff == 1;
		Map<String, Object> map = getStatus();
		return map;
	}
	
	@GetMapping("/sync/{ip}")
	public Map<String, Object> setUrl(@PathVariable String ip) {
		InitConstants.IP = ip;
		Map<String, Object> map = getStatus();
		return map;
	}
	
	@GetMapping("/num/{num}")
	public String num(@PathVariable int num) {
		StopWatch sw = new StopWatch();
    	sw.start();
    	MyThreadPool pool = MyThreadPool.getInstance();
    	ThreadPoolExecutor singlePool = pool.getSinglePool();
        List<CompletableFuture<Void>> futures = IntStream.range(0, num)
        		.mapToObj(i ->CompletableFuture.runAsync(()->{
        			initDataService.save(createSourceData(i));
        		}, singlePool)
        ).collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();
        sw.stop();
        InitConstants.START_ID = InitConstants.START_ID + num;
        return "time length:" + sw.getTime();
	}
	
	
	@GetMapping("/jpabatch/{num}")
    public String insertDatas1(@PathVariable int num) {
		StopWatch sw = new StopWatch();
    	sw.start();
    	/*List<InitData> collect = IntStream.range(1, num)
    			.mapToObj(i -> createSourceData(i))
    			.collect(Collectors.toList());
    	
		initDataService.batchSave(collect);
		InitConstants.START_ID = InitConstants.START_ID + num;*/
		InitData data1=new InitData();
		data1.setId(25L);
		data1.setPlatform("111");

		InitData data2=new InitData();
		data2.setId(26L);
		data2.setPlatform("222");

		InitData data3=new InitData();
		data3.setId(27L);
		data3.setPlatform("333");
		List<InitData> list = new ArrayList<>();
		list.add(data1);
		list.add(data2);
		list.add(data3);
		initDataService.saveAll(list);
		sw.stop();
        return "time length:" + sw.getTime();
    }
	
	@GetMapping("/sqlbatch/{num}")
    public String insertDatas(@PathVariable int num) {
		StopWatch sw = new StopWatch();
    	sw.start();
    	List<InitData> collect = IntStream.range(1, num)
    			.mapToObj(i -> createSourceData(i))
    			.collect(Collectors.toList());
		initDataService.batchSaveAll(collect);
		InitConstants.START_ID = InitConstants.START_ID + num;
		sw.stop();
        return "time length:" + sw.getTime();
    }

	
	@ApiOperation("初始化 列表")
	@GetMapping("/list")
	@ResponseBody
	public ResultBean list(HttpServletRequest request,
			InitDataVo initDataVo,
			@RequestParam(defaultValue="1") int page, 
			@RequestParam(defaultValue="20") int rows,
			@RequestParam(defaultValue="updatedTime") String sidx, 
			@RequestParam(defaultValue="desc") String sord) {
		InitData initData = new InitData();
		BeanUtils.copyProperties(initDataVo, initData);
		
		Page<InitData> pages = initDataService
				.findAll(initData, page, rows, sord, sidx);
		
		return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
	}

	@ApiOperation("初始化 新增")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "uuid", required = true),
		@ApiImplicitParam(name = "platform", required = true),
		@ApiImplicitParam(name = "operation", required = true),
		@ApiImplicitParam(name = "contentId", required = true),
		@ApiImplicitParam(name = "strategyCodes", required = true),
		@ApiImplicitParam(name = "isMishitong", required = true),
		@ApiImplicitParam(name = "accessPlatformId", required = true),
		@ApiImplicitParam(name = "createTime", required = true),
	})
	@PostMapping(value = "/add")
	@ResponseBody
	public ResultBean add(HttpServletRequest request, InitDataVo initDataVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(initDataVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		
		if (isRepeat(initDataVo)) 
			return ResultBean.error(MessageCodes.get(MessageCodes.M980001));

		InitData initData = new InitData();
		BeanUtils.copyProperties(initDataVo, initData);
		
		initDataService.save(initData);
		return ResultBean.ok(initData);
	}
	
	/**
	 * <p><b>Title:</b> isRepeat</p>
	 * <p><b>Description:</b> 判断初始化表 名称是否重复</p>
	 * @author douzi
	 * @param initDataVo
	 */
	private boolean isRepeat(InitDataVo initDataVo) {
		InitData temp = new InitData();
		// temp.setChannelName(initDataVo.getName());
		Optional<InitData> initDataOpt = initDataService.findOne(Example.of(temp));
		if (initDataOpt.isPresent()) {
			InitData initData = initDataOpt.get();
			if (initDataVo.getId() != null && initDataVo.getId() != initData.getId())
				return true;
			else if (initDataVo.getId() == null)
				return true;
		}
		return false;
	}
	
	@ApiOperation("初始化 详情")
	@ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
	@GetMapping(value = "/get")
	@ResponseBody
	public ResultBean get(Long id) {
		InitData initData = initDataService.get(id);
		return ResultBean.ok(initData);
	}
	
	@ApiOperation("初始化 变更")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", required = true),
		@ApiImplicitParam(name = "uuid", required = true),
		@ApiImplicitParam(name = "platform", required = true),
		@ApiImplicitParam(name = "operation", required = true),
		@ApiImplicitParam(name = "contentId", required = true),
		@ApiImplicitParam(name = "strategyCodes", required = true),
		@ApiImplicitParam(name = "isMishitong", required = true),
		@ApiImplicitParam(name = "accessPlatformId", required = true),
		@ApiImplicitParam(name = "createTime", required = true),
	})
	@PutMapping(value = "/edit")
	@ResponseBody
	public ResultBean update(HttpServletRequest request, InitDataVo initDataVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(initDataVo, Constants.VALIDATE_UPDATE);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		
		if (isRepeat(initDataVo)) 
			return ResultBean.error(MessageCodes.get(MessageCodes.M980001));
		
		InitData initData = new InitData();
		BeanUtils.copyProperties(initDataVo, initData);
		return ResultBean.ok(initDataService.merge(initData));
	}
	
	@ApiOperation("初始化 删除")
	@ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
	@DeleteMapping(value = "/del")
	@ResponseBody
	public ResultBean delete(Long id) {
		initDataService.deleteById(id);
		return ResultBean.ok();
	}
	
	/**
	 * <p><b>Title:</b> getStatus</p>
	 * <p><b>Description:</b> 获取状态</p>
	 * @author douzi
	 * @return
	 */
	private Map<String, Object> getStatus() {
		Map<String, Object> map = new HashMap<String, Object>();
		ThreadPoolExecutor tpe = threadPoolD.getThreadPoolExecutor();
		int milliseconds = InitConstants.MINUTE * 60 * 1000;
		
		int sleepTime = milliseconds / InitConstants.ALL_NUM == 0 ? 1
				: InitConstants.ALL_NUM / InitConstants.THREAD_NUM;
		map.put("data", "池队列数:" + tpe.getQueue().size() + 
				"|线程数：" + tpe.getActiveCount() + 
				"|任务数：" + tpe.getTaskCount() +
				"|线程休息时间：" + sleepTime + "ms" +
				"|总任务数：" + InitConstants.ALL_NUM + 
				"|当前执行任务数：" + InitConstants.CURR_NUM + 
				"|同步总开关OFF：" + InitConstants.OFF + 
				"|任务策略：" + InitConstants.TASK + 
				"|同步url：" + InitConstants.MOMS_SYNC_URL);
		return map;
	}
	private InitData createSourceData(int index){
		InitData sd = new InitData();
//		sd.setId((long) (InitConstants.START_ID + index));
    	sd.setContentId(InitConstants.START_ID + index + "");
    	sd.setCreateTime(DateUtil.now());
    	sd.setAccessPlatformId("MCMS");
    	sd.setIsMishitong("0");
    	sd.setOperation("1");
    	sd.setPlatform("199");
    	sd.setStrategyCodes(InitConstants.STRATEGY_IDS);
    	return sd;
    }
}
